package highTech.Thread.threadLocal;

import java.util.Random;

public class ThreadLocalObjectTest {

	//private static ThreadLocal<MyThreadScopeData> threadData=new ThreadLocal<MyThreadScopeData>();
	public static void main(String[] args) {
		for(int i=0;i<2;i++){
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					int data=new Random().nextInt();
					/*System.out.println(Thread.currentThread().getName()+" has put data "+data);
					MyThreadScopeData myThreadScopeData=new MyThreadScopeData();
					myThreadScopeData.setName("name:"+data);
					myThreadScopeData.setAge(data);
					threadData.set(myThreadScopeData);*/
					MyThreadScopeData.getInstance().setName("name:"+data);
					MyThreadScopeData.getInstance().setAge(data);
					new A().get();
					new B().get();
				}
			}).start();
		}

	}
	
	static class A{
		public void get(){
			System.out.println("A:"+Thread.currentThread().getName()+" has get data name:"+
					MyThreadScopeData.getInstance().getName()+",age:"+MyThreadScopeData.getInstance().getAge());
		}
	}
	
	static class B{
		public void get(){
			System.out.println("B:"+Thread.currentThread().getName()+" has get data name:"+
					MyThreadScopeData.getInstance().getName()+",age:"+MyThreadScopeData.getInstance().getAge());
		}
	}

}

class MyThreadScopeData{
	private MyThreadScopeData(){}
	
	private static ThreadLocal<MyThreadScopeData> threadData=new ThreadLocal<MyThreadScopeData>();
	public static /*synchronized*/ MyThreadScopeData getInstance(){
		MyThreadScopeData myThreadScopeData=threadData.get();
		if(myThreadScopeData==null){
			myThreadScopeData=new MyThreadScopeData();
			threadData.set(myThreadScopeData);
		}
		return myThreadScopeData;
	}
	
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}
